﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Accountability4net.Contact;
using System.Data.SqlClient;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace Accountability4net.MSSQLDbProvider
{
    public class SQLDbContact: BaseContact
    {
        SQLDbProvider provider_;
        protected SQLDbContact()
            : base()
        {
        }

        public SQLDbContact(SQLDbProvider provider)
            : this()
        {
            provider_ = provider;
        }

        public void WirePropertyChanged()
        {
            PropertyChanged += SQLDbContact_PropertyChanged;
            ((SQLDbName)Name).PropertyChanged += SQLDbContact_PropertyChanged;
        }

        public override IName Name
        {
            get
            {
                if (name_ == null)
                {
                    name_ = new SQLDbName(provider_, this);
                }
                return name_;
            }
            set
            {
                base.Name = value;
            }
        }
        
        public void SQLDbContact_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            string sql = @"UPDATE [contact]
                SET [id] = @id
                , [email] = @email
                , [name.familyName] = @familyName
                , [name.givenName] = @givenName
                , [name.additionalNames] = @additionalNames
                , [name.namePrefix] = @namePrefix
                , [name.nameSuffix] = @nameSuffix
                , [name.formattedName] = @formattedName
                , [photo] = @photo
                WHERE [id] = @id";
            using (var command = provider_.CreateCommand(sql, provider_.Connection))
            {
                byte[] imageBytes;
                using (var stream = new MemoryStream())
                {
                    if (this.Photo != null)
                    {
                        this.Photo.Save(stream, ImageFormat.Png);
                    }
                    stream.Position = 0;
                    imageBytes = stream.ToArray();
                }
                command.Parameters.AddRange(new SqlParameter[] 
                {
                    new SqlParameter("@id", this.ID)
                    , new SqlParameter("@email", this.Email??String.Empty)
                    , new SqlParameter("@familyName", this.Name.FamilyName??String.Empty)
                    , new SqlParameter("@givenName", this.Name.GivenName??String.Empty)
                    , new SqlParameter("@additionalNames", this.Name.AdditionalNames??String.Empty)
                    , new SqlParameter("@namePrefix", this.Name.NamePrefix??String.Empty)
                    , new SqlParameter("@nameSuffix", this.Name.NameSuffix??String.Empty)
                    , new SqlParameter("@formattedName", this.Name.FormattedName??String.Empty)
                    , new SqlParameter("@photo", imageBytes)
                });
                int rows = command.ExecuteNonQuery();
            }
        }

        public static SQLDbContact Create(SQLDbProvider provider)
        {
            SQLDbContact contact = new SQLDbContact(provider);
            contact.ID = Guid.NewGuid();
            string sql = "INSERT INTO [contact] ([id]) VALUES (@id)";
            using (var command = provider.CreateCommand(sql, provider.Connection))
            {
                command.Parameters.Add(new SqlParameter("@id", contact.ID));
                int rows = command.ExecuteNonQuery();
            }
            contact.WirePropertyChanged();
            return contact;
        }

        public static IContact Retrieve(SQLDbProvider provider, Guid id)
        {
            SQLDbContact contact = new SQLDbContact(provider);
            string sql = "SELECT * FROM [contact] WHERE [id] = @id";
            using (var command = provider.CreateCommand(sql, provider.Connection))
            {
                SqlParameter idParameter = new SqlParameter("@id", id);
                command.Parameters.Add(idParameter);
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        contact.ID = new Guid(provider.GetString(reader, "id"));
                        contact.Email = provider.GetString(reader, "email");
                        contact.Name.FamilyName = provider.GetString(reader, "name.familyName");
                        contact.Name.GivenName = provider.GetString(reader, "name.givenName");
                        contact.Name.AdditionalNames = provider.GetString(reader, "name.additionalNames");
                        contact.Name.NamePrefix = provider.GetString(reader, "name.namePrefix");
                        contact.Name.NameSuffix = provider.GetString(reader, "name.nameSuffix");
                        contact.Name.FormattedName = provider.GetString(reader, "name.formattedName");
                        byte[] buffer = new byte[1000];
                        using (var stream = new MemoryStream())
                        {
                            long index = 0;
                            long count = 0;
                            do
                            {
                                try
                                {
                                    count = reader.GetBytes(reader.GetOrdinal("photo"), index, buffer, 0, buffer.Length);
                                    index += count;
                                    stream.Write(buffer, 0, (int)count);
                                    stream.Flush();
                                }
                                catch (IndexOutOfRangeException)
                                {
                                    // This just means that we have read all we can
                                    break;
                                }
                            } while (count > 0);
                            stream.Position = 0;
                            contact.Photo = Bitmap.FromStream(stream);
                        }

                    }
                    else
                    {
                        return null;
                    }
                    reader.Close();
                }
            }
            contact.WirePropertyChanged();
            return contact;
        }


    }
}
